
import java.util.*;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class CanvasWait
        extends Canvas {

    private int mInterval;
    private int mWidth, mHeight;
    private int xMin, xMax, xStep, xPos, xDir;
    private int yMin, yMax, yStep, yPos, yDir;
    private int minStep, maxStep, rr, gg, bb;

    private Random rnd;
    public MIDlet m = null;

    public CanvasWait()
    {
        mInterval = 100;

        mWidth = getWidth();
        mHeight = getHeight();

        int ofs = 20;
        minStep = 2;
        maxStep = 10;

        xMin = ofs;
        yMin = ofs;
        xMax = mWidth - xMin - ofs;
        yMax = mHeight - yMin - ofs;

        rr = 0;
        gg = 0;
        bb = 0;
        rnd = new Random();
        xStep = rnd.nextInt(maxStep - minStep) + minStep;
        yStep = rnd.nextInt(maxStep - minStep) + minStep;

        xDir = 1;
        yDir = 1;
        xPos = (xMin + xMax) / 2;
        yPos = (yMin + yMax) / 2;

        // Create a Timer to update the display.
        TimerTask task = new TimerTask() {

            public void run()
            {
                repaint();
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 0, mInterval);
    }

    public void paint(Graphics g)
    {
        // Clear the whole screen.
        g.setColor(255, 255, 255);
        g.fillRect(0, 0, mWidth, mHeight);

        xPos = xPos + xStep * xDir;
        yPos = yPos + yStep * yDir;
        char contact = 'X';
        if(xPos >= xMax)
        {
            xDir = -1;
            xPos = xMax;
            yStep = rnd.nextInt(maxStep - minStep) + minStep;
            contact = 'R';
        }
        else if(xPos <= xMin)
        {
            xDir = 1;
            xPos = xMin;
            yStep = rnd.nextInt(maxStep - minStep) + minStep;
            contact = 'L';
        }
        if(yPos >= yMax)
        {
            yDir = -1;
            yPos = yMax;
            xStep = rnd.nextInt(maxStep - minStep) + minStep;
            contact = 'B';
        }
        else if(yPos <= yMin)
        {
            yDir = 1;
            yPos = yMin;
            xStep = rnd.nextInt(maxStep - minStep) + minStep;
            contact = 'T';
        }
        // Now draw the pinwheel.
        if(contact != 'X')
        {
            rr = rnd.nextInt(255);
            gg = rnd.nextInt(255);
            bb = rnd.nextInt(255);
            // g.setColor(128, 0, 0);
            if(m != null) Display.getDisplay(m).vibrate(30);
        }
        g.setColor(rr, gg, bb);
        g.fillArc(xPos, yPos, 10, 10, 0, 360);
    }
}
